package game.editer.view;

import game.data.EffectData;
import hx.display.DisplayObject;
import hx.events.MouseEvent;
import hx.assets.TextureAtlasFuture;
import hx.assets.Atlas;
import hx.layout.FlowLayout;
import hx.layout.AnchorLayoutData;
import hx.display.Scroll;
import hx.display.MovieClip;

using haxe.io.Path;
using StringTools;

/**
 * 创建特效预览界面
 */
class CreateEffectPreviewView extends BaseView {
	override function onInit() {
		super.onInit();

		var scroll = new Scroll();
		this.addChild(scroll);
		scroll.layoutData = new AnchorLayoutData(36, 5, 5, 5);
		scroll.layout = new FlowLayout(30, 30);
		scroll.autoVisible = true;

		var files:Array<String> = sys.FileSystem.readDirectory(EditerStage.projectImagesPath);
		files = files.filter((f) -> StringTools.endsWith(f, ".png"));
		for (file in files) {
			// 判断是否已经存在精灵图资源
			var atlas = EditerStage.roleAssets.getAtlas(file.withoutDirectory().withoutExtension());
			if (atlas != null) {
				var effect = new EffectPreviewDisplay(file.withoutDirectory().withoutExtension());
				scroll.addChild(effect);
			} else {
				var xml = Path.join([EditerStage.projectImagesPath, file.withoutExtension() + ".xml"]);
				var png = Path.join([EditerStage.projectImagesPath, file]);
				if (sys.FileSystem.exists(xml)) {
					new TextureAtlasFuture({
						png: png,
						xml: xml,
						path: png
					}, true).onComplete((atlas) -> {
						EditerStage.roleAssets.atlases.set(file.withoutDirectory().withoutExtension(), atlas);
						var effect = new EffectPreviewDisplay(file.withoutDirectory().withoutExtension());
						scroll.addChild(effect);
					});
				} else {
					trace("xml", xml, "不存在");
				}
			}
		}

		scroll.addEventListener(MouseEvent.CLICK, onClickEvent);
		scroll.addEventListener(MouseEvent.DOUBLE_CLICK, onDoubleClick);
	}

	public var onCreateEffect:EffectData->Void;

	private function onDoubleClick(e:MouseEvent):Void {
		if (e.target is EffectPreviewDisplay) {
			// 创建新的特效
			var effectData:EffectData = new EffectData();
			effectData.name = cast(e.target, EffectPreviewDisplay).id;
			if (onCreateEffect != null) {
				onCreateEffect(effectData);
			}
			this.remove();
		}
	}

	private var __lastClickedDisplay:EffectPreviewDisplay;

	private function onClickEvent(e:MouseEvent):Void {
		if (__lastClickedDisplay != null) {
			__lastClickedDisplay.setSelected(false);
		}
		if (e.target is EffectPreviewDisplay) {
			__lastClickedDisplay = e.target;
			__lastClickedDisplay.setSelected(true);
		}
	}
}
